package cn.xxm.scene.validate.processor;


import cn.xxm.scene.validate.annotation.VNumber;
import cn.xxm.scene.validate.exception.ValidateException;
import cn.xxm.scene.validate.response.ResponseInfo;

@SuppressWarnings("rawtypes")
public class NumberProcessor extends ValidateProcessor {
	private double min;
	private double max;
	private int precision;

	@SuppressWarnings("unchecked")
	public NumberProcessor(VNumber vNumber){
		Class<Enum> enumClass = (Class<Enum>)vNumber.enumClass();
		Enum enumInstance = Enum.valueOf(enumClass, vNumber.enumName());
		if(! (enumInstance instanceof ResponseInfo)) {//枚举类型没实现ResponseInfo则抛异常
			throw new ValidateException("枚举类型<"+enumClass+">未实现接口<"+ResponseInfo.class+">")  ;
		}
		super.setResponseInfo(enumInstance);
		min = vNumber.min();
		max = vNumber.max();
		precision = vNumber.precision();
	}
	
	@Override
	public boolean validate(Object value) {
		if(value == null){
			return false;
		}
		String str = value.toString();
		double num;
		try{
			num = Double.valueOf(str);
		}catch(Exception e){
			return false;
		}
		/** 
		 * 结尾为f、d的数据,string转double正确
		 * 但是转BigDecimal会抛异常，此种情况校验不通过  **/
		int lastIdx = str.length()-1;
		if(!Character.isDigit(str.charAt(lastIdx))){
			return false;
		}
		if(num < min || num > max){
			return false;
		}
		if(precision >= 0){
			int idx = str.lastIndexOf('.');
			int prec = 0;
			if(idx != -1 && idx != lastIdx){
				prec = lastIdx - idx;
			}
			if(prec > precision){
				return false;
			}
		}
		return true;
	}
}
